<template>
	<AdminLayout activeKey="dispute-records" :breadcrumbs="['首页','订单与交易管理','纠纷处理记录']" tabTitle="纠纷处理记录" :loading="isLoading">
		<view class="page">
			<view class="section-header">
				<text class="section-title">纠纷处理记录</text>
				<text class="section-desc">查看和管理所有订单纠纷处理历史</text>
			</view>

			<!-- 统计卡片 -->
			<view class="stats-grid">
				<view class="stat-card">
					<view class="stat-value">{{ statistics.total }}</view>
					<view class="stat-label">总处理数</view>
					<view class="stat-desc">所有纠纷记录</view>
				</view>
				<view class="stat-card">
					<view class="stat-value">{{ statistics.cancelAndRefund }}</view>
					<view class="stat-label">取消退款</view>
					<view class="stat-desc">取消订单并退款</view>
				</view>
				<view class="stat-card">
					<view class="stat-value">{{ statistics.forceComplete }}</view>
					<view class="stat-label">强制完成</view>
					<view class="stat-desc">管理员强制完成</view>
				</view>
				<view class="stat-card">
					<view class="stat-value">{{ statistics.extendTime }}</view>
					<view class="stat-label">延长时间</view>
					<view class="stat-desc">任务时间延长</view>
				</view>
			</view>

			<!-- 筛选工具栏 -->
			<view class="filter-toolbar">
				<input 
					class="search-input" 
					v-model="filters.keyword" 
					placeholder="搜索任务标题或订单ID" 
					@input="onSearchInput"
				/>
				<picker mode="selector" :range="actionOptions" @change="onActionChange">
					<view class="picker-btn">处理类型：{{ filters.action || '全部' }}</view>
				</picker>
				<picker mode="date" @change="onStartDateChange">
					<view class="picker-btn">开始：{{ filters.startDate || '选择日期' }}</view>
				</picker>
				<picker mode="date" @change="onEndDateChange">
					<view class="picker-btn">结束：{{ filters.endDate || '选择日期' }}</view>
				</picker>
				<button class="filter-btn" @click="refreshData">刷新</button>
			</view>

			<!-- 显示统计 -->
			<view class="display-stats">
				<text class="stats-text">数据库总记录：{{ statistics.total }}条</text>
				<text class="stats-text">当前显示：{{ displayList.length }}条</text>
			</view>

			<!-- 记录列表 -->
			<view class="content-area">
				<scroll-view scroll-y class="record-list">
					<view v-for="record in displayList" :key="record._id" class="record-item" :class="record.action">
						<view class="record-header">
							<view class="record-meta">
								<text class="action-tag" :class="record.action">{{ getActionText(record.action) }}</text>
								<text class="record-time">{{ formatTime(record.process_time) }}</text>
							</view>
							<text class="record-admin">处理人：{{ record.admin_name }}</text>
						</view>

						<view class="record-content">
							<text class="task-title">任务：{{ record.task_title }}</text>
							<text class="task-info">订单ID：{{ record.task_id }}</text>
							<text class="task-info">发布者：{{ record.publisher_name }}</text>
							<text class="task-info" v-if="record.receiver_name">接单人：{{ record.receiver_name }}</text>
						</view>

						<view class="record-detail">
							<text class="detail-label">处理原因</text>
							<text class="detail-content">{{ record.reason || '无' }}</text>
						</view>

						<view class="record-detail" v-if="record.result_message">
							<text class="detail-label">处理结果</text>
							<text class="detail-content result-message">{{ record.result_message }}</text>
						</view>

						<!-- 通知状态 -->
						<view class="record-detail" v-if="record.notification_status">
							<text class="detail-label">通知状态</text>
							<view class="notification-status">
								<text class="status-item" v-if="record.notification_status.publisherSent">✓ 已通知发布者</text>
								<text class="status-item" v-if="record.notification_status.participantSent">✓ 已通知执行者</text>
								<text class="status-item error" v-if="record.notification_status.failed && record.notification_status.failed.length > 0">
									✗ 通知失败：{{ record.notification_status.failed.join(', ') }}
								</text>
							</view>
						</view>

						<view class="record-actions">
							<button size="mini" @click="viewTaskDetail(record.task_id)">查看订单</button>
							<button size="mini" type="warn" v-if="canReprocess(record)" @click="reprocessDispute(record)">重新处理</button>
						</view>
					</view>

					<view v-if="displayList.length === 0" class="empty-tip">
						<text class="empty-icon">📋</text>
						<text class="empty-text">暂无纠纷处理记录</text>
					</view>
				</scroll-view>

				<!-- 分页 -->
				<view class="pagination" v-if="pagination.total > 0">
					<button 
						:disabled="pagination.page <= 1" 
						@click="changePage(pagination.page - 1)"
						size="mini"
					>
						上一页
					</button>
					<text class="page-info">{{ pagination.page }} / {{ pagination.totalPages }}</text>
					<button 
						:disabled="pagination.page >= pagination.totalPages" 
						@click="changePage(pagination.page + 1)"
						size="mini"
					>
						下一页
					</button>
				</view>
			</view>
		</view>
	</AdminLayout>
</template>

<script>
import AdminLayout from '@/components/AdminLayout.vue'

export default {
	components: { AdminLayout },
	data() {
		return {
			isLoading: false,
			filters: {
				keyword: '',
				action: '',
				startDate: '',
				endDate: ''
			},
			actionOptions: ['全部', '取消并退款', '强制完成', '延长时间', '介入协调'],
			allRecords: [],
			displayList: [],
			statistics: {
				total: 0,
				cancelAndRefund: 0,
				forceComplete: 0,
				extendTime: 0,
				adminMediate: 0
			},
			pagination: {
				page: 1,
				pageSize: 20,
				total: 0,
				totalPages: 0
			},
			searchTimer: null
		}
	},

	mounted() {
		this.loadDisputeRecords()
	},

	methods: {
		// 加载纠纷处理记录
		async loadDisputeRecords() {
			this.isLoading = true
			try {
				const { result } = await uniCloud.callFunction({
					name: 'getDisputeRecords',
					data: {
						isAdmin: true,
						page: this.pagination.page,
						pageSize: this.pagination.pageSize
					}
				})

				if (result && result.code === 200) {
					this.allRecords = result.data.records || []
					this.pagination = {
						page: result.data.page || 1,
						pageSize: result.data.pageSize || 20,
						total: result.data.total || 0,
						totalPages: result.data.totalPages || 0
					}
					
					// 计算统计数据
					this.calculateStatistics()
					
					// 应用筛选
					this.applyFilters()
					
					uni.showToast({ title: `加载${this.allRecords.length}条记录`, icon: 'success', duration: 1500 })
				} else {
					throw new Error(result?.msg || '加载失败')
				}
			} catch (error) {
				console.error('加载纠纷记录失败:', error)
				uni.showToast({ title: '加载失败，使用演示数据', icon: 'none' })
				this.loadMockData()
			} finally {
				this.isLoading = false
			}
		},

		// 加载模拟数据
		loadMockData() {
			this.allRecords = [
				{
					_id: '1',
					task_id: 'task_001',
					task_title: '代买午餐',
					publisher_name: '张三',
					receiver_name: '李四',
					action: 'cancel_and_refund',
					reason: '发布者要求取消，接单人未开始执行',
					result_message: '任务已取消并安排退款，退款金额：¥50.00',
					admin_name: '管理员A',
					process_time: Date.now() - 3600000,
					notification_status: {
						publisherSent: true,
						participantSent: true,
						failed: []
					}
				},
				{
					_id: '2',
					task_id: 'task_002',
					task_title: '快递代取',
					publisher_name: '王五',
					receiver_name: '赵六',
					action: 'force_complete',
					reason: '接单人已完成但系统未更新，手动标记完成',
					result_message: '任务已强制完成',
					admin_name: '管理员B',
					process_time: Date.now() - 7200000,
					notification_status: {
						publisherSent: true,
						participantSent: true,
						failed: []
					}
				},
				{
					_id: '3',
					task_id: 'task_003',
					task_title: '帮忙送文件',
					publisher_name: '陈老师',
					receiver_name: '小明',
					action: 'extend_time',
					reason: '接单人遇到特殊情况，双方协商延长时间',
					result_message: '任务时间已延长7天',
					admin_name: '管理员A',
					process_time: Date.now() - 86400000,
					notification_status: {
						publisherSent: true,
						participantSent: true,
						failed: []
					}
				},
				{
					_id: '4',
					task_id: 'task_004',
					task_title: '代购图书',
					publisher_name: '小李',
					receiver_name: '小王',
					action: 'admin_mediate',
					reason: '双方对任务完成标准存在争议，需要介入协调',
					result_message: '已介入协调处理，将联系双方沟通',
					admin_name: '管理员C',
					process_time: Date.now() - 172800000,
					notification_status: {
						publisherSent: true,
						participantSent: true,
						failed: []
					}
				}
			]
			
			this.pagination = {
				page: 1,
				pageSize: 20,
				total: this.allRecords.length,
				totalPages: 1
			}
			
			this.calculateStatistics()
			this.applyFilters()
		},

		// 计算统计数据
		calculateStatistics() {
			this.statistics = {
				total: this.allRecords.length,
				cancelAndRefund: this.allRecords.filter(r => r.action === 'cancel_and_refund').length,
				forceComplete: this.allRecords.filter(r => r.action === 'force_complete').length,
				extendTime: this.allRecords.filter(r => r.action === 'extend_time').length,
				adminMediate: this.allRecords.filter(r => r.action === 'admin_mediate').length
			}
		},

		// 应用筛选
		applyFilters() {
			let filteredList = [...this.allRecords]

			// 关键词搜索
			if (this.filters.keyword && this.filters.keyword.trim()) {
				const keyword = this.filters.keyword.trim().toLowerCase()
				filteredList = filteredList.filter(record => {
					const title = (record.task_title || '').toLowerCase()
					const taskId = (record.task_id || '').toLowerCase()
					return title.includes(keyword) || taskId.includes(keyword)
				})
			}

			// 处理类型筛选
			if (this.filters.action && this.filters.action !== '全部') {
				const actionKey = this.getActionKey(this.filters.action)
				filteredList = filteredList.filter(record => record.action === actionKey)
			}

			// 日期筛选
			if (this.filters.startDate || this.filters.endDate) {
				filteredList = filteredList.filter(record => {
					const recordDate = new Date(record.process_time)
					const startDate = this.filters.startDate ? new Date(this.filters.startDate) : null
					const endDate = this.filters.endDate ? new Date(this.filters.endDate + ' 23:59:59') : null
					
					let passFilter = true
					if (startDate && recordDate < startDate) passFilter = false
					if (endDate && recordDate > endDate) passFilter = false
					
					return passFilter
				})
			}

			// 按时间倒序排序
			filteredList.sort((a, b) => b.process_time - a.process_time)

			this.displayList = filteredList
		},

		// 获取处理类型文本
		getActionText(action) {
			const actionMap = {
				'cancel_and_refund': '取消并退款',
				'force_complete': '强制完成',
				'extend_time': '延长时间',
				'admin_mediate': '介入协调'
			}
			return actionMap[action] || action
		},

		// 获取处理类型key
		getActionKey(text) {
			const keyMap = {
				'取消并退款': 'cancel_and_refund',
				'强制完成': 'force_complete',
				'延长时间': 'extend_time',
				'介入协调': 'admin_mediate'
			}
			return keyMap[text] || text
		},

		// 时间格式化
		formatTime(v) {
			if (!v) return '--'
			const d = new Date(v)
			const p = n => String(n).padStart(2, '0')
			return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
		},

		// 判断是否可以重新处理
		canReprocess(record) {
			// 介入协调的记录可以重新处理
			return record.action === 'admin_mediate'
		},

		// 查看订单详情
		viewTaskDetail(taskId) {
			uni.navigateTo({
				url: `/pages/admin/order-detail/index?id=${taskId}`
			})
		},

		// 重新处理纠纷
		reprocessDispute(record) {
			uni.navigateTo({
				url: `/pages/admin/order-management/index?taskId=${record.task_id}&action=dispute`
			})
		},

		// 筛选事件
		onActionChange(e) {
			const index = Number(e.detail.value)
			this.filters.action = this.actionOptions[index]
			this.applyFilters()
		},

		onStartDateChange(e) {
			this.filters.startDate = e.detail.value
			this.applyFilters()
		},

		onEndDateChange(e) {
			this.filters.endDate = e.detail.value
			this.applyFilters()
		},

		onSearchInput(e) {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
			}
			this.searchTimer = setTimeout(() => {
				this.applyFilters()
			}, 300)
		},

		// 刷新数据
		refreshData() {
			this.loadDisputeRecords()
		},

		// 分页
		changePage(page) {
			this.pagination.page = page
			this.loadDisputeRecords()
		}
	}
}
</script>

<style scoped>
.page {
	padding: 20rpx;
	min-height: calc(100vh - 140rpx);
	display: flex;
	flex-direction: column;
}

.section-header {
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.section-desc {
	font-size: 26rpx;
	color: #666;
	display: block;
}

/* 统计卡片 */
.stats-grid {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(180rpx, 1fr));
	gap: 20rpx;
	margin-bottom: 30rpx;
}

.stat-card {
	background: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	text-align: center;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.06);
	transition: all 0.3s;
}

.stat-card:hover {
	box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.12);
}

.stat-value {
	font-size: 48rpx;
	font-weight: 700;
	color: #007aff;
	margin-bottom: 8rpx;
}

.stat-label {
	font-size: 26rpx;
	color: #666;
}

.stat-desc {
	font-size: 20rpx;
	color: #999;
	margin-top: 4rpx;
}

/* 筛选工具栏 */
.filter-toolbar {
	display: flex;
	align-items: center;
	gap: 16rpx;
	margin-bottom: 20rpx;
	flex-wrap: wrap;
}

.search-input {
	flex: 2;
	min-width: 300rpx;
	max-width: 500rpx;
	background: #fff;
	border-radius: 16rpx;
	padding: 20rpx 24rpx;
	border: 2rpx solid #e0e0e0;
	font-size: 30rpx;
	height: 88rpx;
	box-sizing: border-box;
	transition: all 0.3s;
}

.search-input:focus {
	border-color: #007aff;
	box-shadow: 0 0 0 4rpx rgba(0, 122, 255, 0.1);
}

.picker-btn {
	padding: 16rpx 20rpx;
	background: #fff;
	border-radius: 12rpx;
	border: 2rpx solid #f0f0f0;
	font-size: 26rpx;
	color: #333;
	white-space: nowrap;
}

.filter-btn {
	padding: 16rpx 24rpx;
	background: #007aff;
	color: #fff;
	border-radius: 12rpx;
	font-size: 26rpx;
	border: none;
}

/* 显示统计 */
.display-stats {
	display: flex;
	align-items: center;
	gap: 20rpx;
	margin-bottom: 20rpx;
	padding: 16rpx 20rpx;
	background: #f8f9fa;
	border-radius: 12rpx;
	border: 1rpx solid #e9ecef;
}

.stats-text {
	font-size: 24rpx;
	color: #6c757d;
}

.stats-text:first-child {
	font-weight: 600;
	color: #495057;
}

/* 内容区域 */
.content-area {
	flex: 1;
	display: flex;
	flex-direction: column;
	min-height: 0;
}

.record-list {
	flex: 1;
	overflow-y: auto;
	min-height: 400rpx;
	max-height: calc(100vh - 400rpx);
}

/* 记录项 */
.record-item {
	background: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 16rpx;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.06);
	border-left: 6rpx solid transparent;
	transition: all 0.3s;
}

.record-item:hover {
	box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.12);
}

.record-item.cancel_and_refund {
	border-left-color: #ff4d4f;
}

.record-item.force_complete {
	border-left-color: #52c41a;
}

.record-item.extend_time {
	border-left-color: #1890ff;
}

.record-item.admin_mediate {
	border-left-color: #faad14;
}

.record-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 16rpx;
}

.record-meta {
	display: flex;
	align-items: center;
	gap: 12rpx;
	flex-wrap: wrap;
}

.action-tag {
	padding: 6rpx 14rpx;
	border-radius: 12rpx;
	font-size: 24rpx;
	font-weight: 600;
	color: #fff;
}

.action-tag.cancel_and_refund {
	background: #ff4d4f;
}

.action-tag.force_complete {
	background: #52c41a;
}

.action-tag.extend_time {
	background: #1890ff;
}

.action-tag.admin_mediate {
	background: #faad14;
}

.record-time {
	font-size: 24rpx;
	color: #999;
}

.record-admin {
	font-size: 24rpx;
	color: #666;
}

.record-content {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	margin-bottom: 16rpx;
}

.task-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
}

.task-info {
	font-size: 24rpx;
	color: #666;
}

.record-detail {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 16rpx;
	margin-bottom: 12rpx;
}

.detail-label {
	font-size: 24rpx;
	color: #999;
	display: block;
	margin-bottom: 8rpx;
}

.detail-content {
	font-size: 26rpx;
	color: #333;
	line-height: 1.6;
	display: block;
}

.result-message {
	color: #52c41a;
	font-weight: 500;
}

.notification-status {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.status-item {
	font-size: 24rpx;
	color: #52c41a;
}

.status-item.error {
	color: #ff4d4f;
}

.record-actions {
	display: flex;
	gap: 12rpx;
	justify-content: flex-end;
	flex-wrap: wrap;
	margin-top: 8rpx;
}

.record-actions button {
	padding: 12rpx 20rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	border: none;
	transition: all 0.3s;
}

/* 空状态 */
.empty-tip {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 20rpx;
	text-align: center;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 20rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

/* 分页 */
.pagination {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 20rpx;
	margin-top: 20rpx;
	padding: 20rpx;
	background: #fff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.06);
}

.page-info {
	font-size: 26rpx;
	color: #666;
	min-width: 120rpx;
	text-align: center;
}

.pagination button {
	padding: 12rpx 20rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	border: 1rpx solid #dee2e6;
	background: #fff;
	color: #007aff;
	transition: all 0.3s;
}

.pagination button:disabled {
	background: #f8f9fa;
	color: #6c757d;
	cursor: not-allowed;
}

.pagination button:not(:disabled):hover {
	background: #007aff;
	color: #fff;
}

/* 响应式 */
@media (max-width: 750rpx) {
	.stats-grid {
		grid-template-columns: repeat(2, 1fr);
	}
	
	.filter-toolbar {
		flex-direction: column;
		align-items: stretch;
	}
	
	.search-input {
		max-width: 100%;
	}
}
</style>

